<template>
	<div class="main-con">
		<el-form class="form-con" :model="assetForm" label-suffix=": " ref="form" size="small" label-width="115px">
			<el-form-item label="申请单标题" prop="orderTitle" :rules="{ required: true, message: '请输入申请单标题', trigger: 'blur' }">
				<el-input v-model="assetForm.orderTitle" style="width: 50%"></el-input>
			</el-form-item>
			<el-form-item class="pro-label" prop="proCode" :rules="{ required: true, message: '请先选择录入的资产所属的项目', trigger: 'blur' }">
				<template slot="label">
					所属项目
					<el-tooltip class="item" effect="light" content="请先选择录入的资产所属的项目" placement="top">
						<img style="width: 15px;height: 15px;color: rgba(180, 180, 180, 1);" src="@/assets/image/serverRoom/question.svg" /> </el-tooltip
					>:
				</template>
				<el-button type="text" class="text-btn-table" size="medium" @click="addProject">请选择所属项目</el-button>
				<el-table :data="projectList" stripe class="systemTable" style="width: 60%" empty-text=" ">
					<el-table-column prop="proName" label="项目名称"> </el-table-column>
					<el-table-column prop="proCode" label="项目编号"> </el-table-column>
					<el-table-column prop="creater" label="项目负责人"> </el-table-column>
				</el-table>
			</el-form-item>
			<el-form-item prop="assetList" label="登记资产清单" :rules="{ required: true, validator: validAssetList, trigger: 'blur' }">
				<el-button icon="el-icon-circle-plus" type="text" size="medium" class="text-btn-table" @click="addAsset">添加</el-button>
				<el-table :data="assetForm.assetList" stripe class="systemTable" style="width: 80%" empty-text=" ">
					<el-table-column prop="assetType" label="资产类型" min-width="120">
						<template slot-scope="{ row, $index }">
							<el-form-item class="form-item-column" :prop="'assetList.' + $index + '.assetType'" :rules="[{ required: true, message: '请选择', trigger: 'change' }]">
								<el-select v-model="row.assetType" placeholder="请选择" clearable filterable>
									<el-option v-for="item in assetType" :key="item.resourceTypeId" :label="item.name" :value="item.resourceTypeId"> </el-option>
								</el-select>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column prop="assetModel" label="资产型号" min-width="120">
						<template slot-scope="{ row, $index }">
							<el-form-item class="form-item-column" :prop="'assetList.' + $index + '.assetModel'" :rules="[{ required: true, message: '请输入', trigger: 'blur' }]">
								<el-input v-model="row.assetModel" placeholder="请输入" />
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column prop="assetSerialNum" label="资产序列号" min-width="160">
						<template slot-scope="{ row, $index }">
							<el-form-item class="form-item-column" :prop="'assetList.' + $index + '.assetSerialNum'" :rules="[{ required: true, validator: validateSerialNum, message: '请输入', trigger: 'blur' }]">
								<div style="display: flex;align-items: center;">
									<el-input v-model="row.assetSerialNum" placeholder="请输入" />
									<el-button class="text-btn-table" type="text" size="medium" @click="imgOCR(row, $index)">图片识别</el-button>
								</div>
							</el-form-item>
						</template>
						<template slot="header">
							<div style="display: flex;align-items: center;">
								资产序列号
								<el-tooltip style="margin-left: 8px;" effect="light" placement="top">
									<div style="text-align: center;" slot="content">可使用扫码枪录入，需要将光标放在数据要传输的位置<br />也可导入图片进行识别图片中的序列号</div>
									<img style="width: 15px;height: 15px;color: rgba(180, 180, 180, 1);" src="@/assets/image/serverRoom/question.svg" />
								</el-tooltip>
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="assetPlace" label="资产位置" min-width="110">
						<template slot-scope="{ row, $index }">
							<el-form-item class="form-item-column" :prop="'assetList.' + $index + '.assetPlace'" :rules="[{ required: true, message: '请选择', trigger: 'change' }]">
								<el-select v-model="row.assetPlace" placeholder="请选择" clearable filterable>
									<el-option v-for="item in assetLocation" :key="item.oid" :label="item.name" :value="item.oid"> </el-option>
								</el-select>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column prop="manufacturerId" label="生产厂商" min-width="110">
						<template slot-scope="{ row, $index }">
							<el-form-item class="form-item-column" :prop="'assetList.' + $index + '.manufacturerId'" :rules="[{ required: true, message: '请选择', trigger: 'change' }]">
								<el-select v-model="row.manufacturerId" placeholder="请选择" clearable filterable>
									<el-option v-for="item in assetManufacturer" :key="item.oid" :label="item.name" :value="item.oid"> </el-option>
								</el-select>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column width="100" label="操作" align="center">
						<template v-slot="scope">
							<el-button class="text-btn-table" type="text" size="medium" @click="copyRow(scope.row)">复制</el-button>
							<el-button class="text-btn-table" type="text" size="medium" @click="removeAsset(scope.$index)">移除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-form-item>
			<el-form-item prop="fileId" label="到货验收单" :rules="{ required: true, message: '请上传到货验收单', trigger: 'blur' }">
				<div style="display: flex;">
					<div class="file-con" v-for="(item, index) in fileList" :key="index">
						<i class="el-icon-close remove-file" @click="removeFile(index)"></i>
						<el-image class="image" :src="item.file" fit="fill"></el-image>
					</div>
					<el-upload class="upload-demo" :auto-upload="false" action="#" :on-progress="uploadProgressHandler" :on-change="uploadChangeHandler" :before-upload="beforeUpload" :show-file-list="false">
						<el-button size="small" type="primary1" :show-file-list="false" icon="el-icon-upload2">点击上传</el-button>
						<div slot="tip" class="el-upload__tip">(请上传到货验收单，可上传多张，支持扩展名：PDF .JPG...)</div>
					</el-upload>
				</div>
			</el-form-item>
			<el-form-item label="备注" prop="">
				<el-input type="textarea" v-model="assetForm.notes" :autosize="{ minRows: 3 }" style="width: 50%" maxlength="200" show-word-limit></el-input>
			</el-form-item>
		</el-form>
		<div class="bottom-btn">
			<el-button @click="cancelForm">取消</el-button>
			<el-button @click="saveAssetTemp">保存草稿</el-button>
			<el-button type="primary" @click="onSubmit">提交审核</el-button>
		</div>
		<model-dialog ref="modelDialog">
			<template v-slot:dialog-content>
				<!--这里是slot 绑定的数据 包含列表数据 是否显示按钮-->
				<!-- <base-dict-model ref="modelContent" :table-info-data="tableInfoData" /> -->
				<select-project ref="modelContent" @onsubmit="projectSubmit" @cancel="cancelProject" />
			</template>
		</model-dialog>
		<asset-flow-send
			v-if="showFlowSend"
			@close="closeFlowSend"
			:wfClassId="wfClassId"
			:checkType="checkFlowType"
			@ok="FlowSendsave"
			:instNodeId="instNodeId"
			:sendtype="sendtype"
			:wfUrl="wfUrl"
			:formData="assetForm"
		></asset-flow-send>
	</div>
</template>
<script>
	import assetFlowMixin from '@/mixins/assetFlowMixin'
	import ModelDialog from '@/views/components/ModelDialog'
	import selectProject from './models/selectProject'
	import { selectDictItems } from '@/system/api/dictionaryManage'
	import assetApi from '@/api/assetApi'
	import { getAction, postAction } from '@/utils/httpUtil'
	import config from '@/tools/config'
	export default {
		name: 'assetAdd',
		components: {
			ModelDialog,
			selectProject,
		},
		mixins: [assetFlowMixin],
		data() {
			return {
				assetForm: {
					orderTitle: '',
					notes: '',
					fileId: '',
					project: {},
					proCode: '',
					assetList: [],
					wfClassId: '',
				},
				projectList: [],
				fileList: [],
				showProjectWin: false,
				assetType: [], //资产类型
				assetLocation: [], // 资产位置
				assetManufacturer: [], // 生产厂商
				wfClassId: '',
				wfUrl: {
					getSendToUrl: '/assetManage/getSendTo',
					sendToUrl: '/assetManage/sendTo',
					getBackToUrl: '/assetManage/getBackTo',
					backToUrl: '/assetManage/backTo',
					getStartToUrl: '/assetManage/getStartTo',
					startToUrl: '/assetManage/assetSubmit',
				},
			}
		},
		mounted() {
			const { params, query } = this.$route
			if (params) {
				this.assetForm.wfClassId = params.wfId
				this.wfClassId = params.wfId
			}
			if (query && query.id) {
				this.loadData(query.id)
			}
			this.selectAssetType()
			// this.commonLoadDic('资产类型', 'assetType')
			// 资产位置
			// selectDictItems({ code: 'assetPlace' }).then(res => {
			// 	this.assetLocation = res.info
			// })
			this.commonLoadDic('资产位置', 'assetLocation')
			this.commonLoadDic('生产厂商', 'assetManufacturer')
		},
		methods: {
			loadData(id) {
				getAction(assetApi.assetManage.detial + id).then(res => {
					if (res.success && res.info) {
						this.assetForm = res.info
						// 设置所属项目
						// this.projectList = [res.info.project]
						this.assetForm.project = {
							proCode: res.info.proCode,
							proName: res.info.proName,
						}
						if (!this.assetForm.wfClassId) {
							this.assetForm.wfClassId = this.wfClassId
						}
						if (this.assetForm.fileId) {
							let fileNameList = this.assetForm.fileId.split(',')
							fileNameList.forEach(fileName => {
								// `wiremap.g/acceptance_form/${fileName}`
								this.fileList.push({ name: fileName, path: fileName, file: `${config.base_url}wiremap.g/acceptance_form/${fileName}` })
								// this.fileList.push({ name: fileName, file: 'http://localhost:9090/wiremap.g/acceptance_form/20240110150859934.jpg' })
							})
						}
						this.projectList = [
							{
								proCode: res.info.proCode,
								proName: res.info.proName,
								proLeaderId: res.info.proLeaderId,
								creater: res.info.proLeaderName,
							},
						]
					}
				})
			},
			validateSerialNum(rule, value, callback) {
				if (!value) {
					return callback(new Error('请输入'))
				}
				if (this.assetForm.assetList && this.assetForm.assetList.length > 0) {
					let assetList = this.assetForm.assetList.filter(item => {
						return item.assetSerialNum == value
					})
					if (assetList.length > 1) {
						callback(new Error('资产序列号已存在'))
					} else {
						callback()
					}
				} else {
					callback()
				}
			},
			// loadManufacturer() {
			// 	getAction(assetApi.asset.queryByCode, { name: '生产厂商' }).then(res => {
			// 		this.assetManufacturer = res.info
			// 	})
			// },
			selectAssetType() {
				getAction(assetApi.asset.selectAssetType).then(res => {
					this.assetType = res.info
				})
			},
			commonLoadDic(type, objStr) {
				getAction(assetApi.asset.queryByCode, { name: type }).then(res => {
					this[objStr] = res.info
				})
			},
			validAssetList(rule, value, callback) {
				if (!this.assetForm.assetList || this.assetForm.assetList.length === 0) {
					callback(new Error('请完善资产信息!'))
				} else {
					callback()
				}
			},
			addProject() {
				this.showProjectWin = true
				this.$refs.modelDialog.showDialogInfo('选择项目')
			},
			projectSubmit(row) {
				if (row) {
					this.projectList = [row]
					this.assetForm.project = { ...row }
					this.assetForm.proCode = row.proCode
					this.$refs.modelDialog.closeDialog()
				}
			},
			cancelProject() {
				this.$refs.modelDialog.closeDialog()
			},
			addAsset() {
				// if (this.assetForm.assetList.length > 0) {
				// 	this.assetForm.assetList.push({ ...this.assetForm.assetList[this.assetForm.assetList.length - 1] })
				// } else {
				this.assetForm.assetList.push({})
				// }
			},
			copyRow(row) {
				this.assetForm.assetList.push({ ...row })
			},
			removeAsset(index) {
				this.assetForm.assetList.splice(index, 1)
			},
			uploadProgressHandler(event, file, fileList) {
				debugger
			},
			uploadChangeHandler(file, fileList) {
				let imgUrl = URL.createObjectURL(file.raw)
				let formData = new FormData()
				formData.append('files', file.raw)
				postAction(assetApi.assetManage.fileSet, formData, 1).then(res => {
					if (res.success) {
						this.fileList.push({ name: file.name, path: res.info.path, file: imgUrl })
						// this.assetForm.fileId = this.assetForm.fileId ? `${this.assetForm.fileId},${res.info.path}` : res.info.path
					}
				})
			},
			beforeUpload(file) {
				if (file.type != 'image/jpeg' && file.type != 'application/pdf') {
					this.$message.error('只支持pdf和jpg格式文件!')
					return false
				}
				let hasFile = this.fileList.findIndex(item => {
					return item.name == file.name
				})
				if (hasFile > -1) {
					this.$message.error('上传文件重复!')
					return false
				}
			},
			removeFile(index) {
				this.fileList.splice(index, 1)
			},
			cancelForm() {
				this.messageBox('确定取消将丢失未保存的信息！').then(res => {
					if (res.action) {
						this.$refs.form.resetFields()
						this.$router.go(-1)
					}
				})
			},
			saveAssetTemp() {
				/**
				 * @todo
				 */
				let nameList = []
				this.fileList.forEach(file => {
					nameList.push(file.path)
				})
				this.assetForm.fileId = nameList.join(',')
				postAction(assetApi.assetManage.add, this.assetForm, 2).then(res => {
					if (res.success) {
						this.$router.go(-1)
					}
				})
			},
			// onSubmit() {
			// 	this.$refs.form.validate(valid => {
			// 		if (valid) {
			// 			this.messageBox('资产信息确认无误，提交审核?').then(res => {
			// 				if (res.action) {
			// 					postAction(assetApi.assetManage.assetSubmit, this.assetForm, 2).then(res => {
			// 						if (res.success) {
			// 							this.$router.go(-1)
			// 						}
			// 					})
			// 				}
			// 			})
			// 		}
			// 	})
			// },
			onSubmit() {
				let nameList = []
				this.fileList.forEach(file => {
					nameList.push(file.path)
				})
				this.assetForm.fileId = nameList.join(',')
				this.$refs.form.validate(valid => {
					if (valid) {
						this.showFlowSend = true
						this.checkFlowType = 1
						this.instNodeId = this.assetForm.wfInstNodeId
						this.sendtype = 0
					}
				})
			},
			FlowSendsave() {
				this.$message.success('操作成功!')
				this.$router.go(-1)
			},
			/**
			 * 图片识别
			 * @param {当前行} row
			 * @param {行index} index
			 */
			imgOCR(row, index) {
				/**
				 * @todo
				 */
			},
		},
	}
</script>

<style lang="scss" scoped>
	.main-con {
		background: #ffffff;
		padding: 20px 15px;
		position: relative;
	}

	.form-con {
		// width: 80%;
		height: calc(100% - 50px);
		overflow-y: auto;
	}

	.pro-label {
		/deep/.el-form-item__label {
			display: flex;
			justify-content: end;
			align-items: center;
		}
	}

	.text-btn-table {
		color: #409eff !important;
	}

	.file-con {
		width: 82px;
		height: 62px;
		border: 1px solid #7bc6b5;
		margin-right: 15px;
		border-radius: 6px;
		position: relative;
	}

	.image {
		width: 80px;
		height: 60px;
		border-radius: 6px;
	}

	.bottom-btn {
		text-align: center;
		position: absolute;
		bottom: 20px;
		width: calc(100% - 30px);
	}

	.remove-file {
		position: absolute;
		right: -5px;
		top: -5px;
		z-index: 10;
		color: red;
		background: #ffffff;
		border-radius: 50%;
		font-size: 16px;
		box-shadow: 0px 0px 12px 0px rgba(129, 155, 151, 0.3);
		cursor: pointer;
	}
</style>
